package com.ebt.m.wiki.view;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.GradientDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.ebt.m.AppContext;
import com.ebt.m.R;
import com.ebt.m.activity.WebBaseActivity;
import com.ebt.m.data.bean.ResponseProductTag;
import com.ebt.m.data.bean.UserInfo;
import com.ebt.m.data.entity.NewProductInfo;
import com.ebt.m.data.entity.ProductTag;
import com.ebt.m.proposal_v2.utils.ProposalUtils;
import com.ebt.m.utils.DateUtils;
import com.ebt.m.commons.utils.Logger;
import com.ebt.m.utils.TalkingDataUtil;
import com.ebt.m.utils.imageloader.ImageLoader;
import com.ebt.m.utils.imageloader.ImageLoaderUtil;
import com.ebt.m.commons.buscomponent.listview.IView;
import com.ebt.m.wiki.ActProductDetail;
import com.jakewharton.rxbinding2.view.RxView;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.concurrent.TimeUnit;


/**
 * @author Michael.li
 */
public class ProductItemView1 extends IView {
    //1正常模式2编辑模式
    public static final int MODE_NORMAL = 1;
    public static final int MODE_EDIT = 2;

    private NewProductInfo currentProduct;

    private TextView mName, mDescription;
    private TextView txtCName;
    private CheckBox mSelect;// 是否显示 复选框
    private ImageView mThumbnail;
    private LinearLayout mLabelContainer;

    private RelativeLayout mContent;
    private TextView mActionInsurance;
    private int dateType = 1;
    public static final int DATATYPE_UNREGISTED = 1;//未注册
    public static final int DATATYPE_REGISTED = 2;//已注册
    public static final int DATATYPE_FOLLOWED = 3;//关注列表
    public static final int DATATYPE_SEARCHED = 4;//搜索列表

    private int flag;
    public static final int FLAG_DYNAMIC = 99;

    public ProductItemView1(Context context) {
        this(context, 0);
    }

    /**
     * @param context
     */
    public ProductItemView1(Context context, int dataType) {
        super(context);
        LayoutInflater inflater = LayoutInflater.from(context);
        inflater.inflate(R.layout.wiki_item_product, this);
        mName = (TextView) findViewById(R.id.wiki_product_name);
        txtCName = (TextView) findViewById(R.id.cname);
        mThumbnail = (ImageView) findViewById(R.id.wiki_product_thumbnail);
        mDescription = (TextView) findViewById(R.id.wiki_product_description);
        mSelect = (CheckBox) findViewById(R.id.wiki_product_select);
        mLabelContainer = (LinearLayout) findViewById(R.id.label_container);
        mContent = (RelativeLayout) findViewById(R.id.content);
        mActionInsurance = findViewById(R.id.action_insurance);
        this.dateType = dataType;
        txtCName.setVisibility(dateType == DATATYPE_SEARCHED ? VISIBLE : GONE);
        RxView.clicks(mContent)
                .throttleFirst(400, TimeUnit.MILLISECONDS)
                .subscribe(aVoid -> {
                    HashMap kv = new HashMap();
                    kv.put("product_id", String.valueOf(currentProduct.getProductId()));
                    kv.put("product_name", currentProduct.getName());
                    UserInfo userInfo = AppContext.getCurrentUser();
                    kv.put("agentId", String.valueOf(userInfo.getUserId()));
                    TalkingDataUtil.onEventWithParams(TalkingDataUtil.TYPE_OPEN_PRODOCT_V270, kv);

                    if (flag == FLAG_DYNAMIC) {
                        if (currentProduct.isMain()) {
                            ProposalUtils.startMakingProposalFromDynamic(getContext(), currentProduct.getProductId());
                        } else {
                            startProductDetail();
                        }
                    } else {
                        startProductDetail();
                    }
                });

        RxView.clicks(mActionInsurance)
                .throttleFirst(400, TimeUnit.MILLISECONDS)
                .subscribe(aVoid -> {
                    gotoInsurance();
                });
    }

    private void gotoInsurance() {
        try {
            TalkingDataUtil.onEvent(TalkingDataUtil.TYPE_BO_TRACE);
            Intent webIntent = new Intent(getContext(), WebBaseActivity.class);
            Bundle bundle = new Bundle();
            bundle.putString(WebBaseActivity.WEB_TYPE_TITLE, "在线投单");
            bundle.putInt(WebBaseActivity.WEB_TYPE_FRAGMENT, WebBaseActivity.FRAGMENT_4NEW_BASE);
            bundle.putBoolean(WebBaseActivity.WEB_TYPE_HIDE_TOOLBAR, true);
            bundle.putString(WebBaseActivity.WEB_TYPE_LINK, currentProduct.getInsuranceUrl());
            webIntent.putExtras(bundle);
            getContext().startActivity(webIntent);
        } catch (Exception e) {
            Logger.e(e);
        }
    }

    public void addFlag(int flag) {
        this.flag = flag;
    }

    @Override
    public void update(Object... args) {
        NewProductInfo product = (NewProductInfo) args[0];
        int mode = 0;
        boolean edit = false;
        boolean isShowBar = false;
        currentProduct = product;
        txtCName.setVisibility(dateType == DATATYPE_SEARCHED ? VISIBLE : GONE);
        mName.setText(product.getName());
        txtCName.setText(product.getBrandShortName());
        mDescription.setText(product.getDescription());
        mSelect.setVisibility(edit ? VISIBLE : GONE);
        boolean canInsuranceOnline = (currentProduct.getIsOpenInsurance() == 1) && (!TextUtils.isEmpty(currentProduct.getInsuranceUrl()));
        mActionInsurance.setVisibility(canInsuranceOnline ? View.VISIBLE : View.GONE);
        String imgUrl = product.getThumbnail();
        ImageLoaderUtil.getInstance().loadImage(getContext(), new ImageLoader.Builder().url(imgUrl).imgView(mThumbnail).build());
        drawLabels(product.getTagInfo());
        try {
            if (args.length > 1) {
                boolean isRecommond = (boolean) args[1];
                if (isRecommond)
                    txtCName.setVisibility(View.VISIBLE);
            }
        } catch (Exception e) {
            Logger.e(e);
        }
    }

    /**
     * 填充数据
     *
     * @param product
     * @param edit    是否编辑模式
     */
    public void setProductInfo(NewProductInfo product, int mode, boolean edit, boolean isShowBar) {
        currentProduct = product;
        mName.setText(product.getName());
        txtCName.setText(product.getCompanyShortName());
        mDescription.setText(product.getDescription());
        mSelect.setVisibility(edit ? VISIBLE : GONE);
        String imgUrl = product.getThumbnail();
        ImageLoaderUtil.getInstance().loadImage(getContext(), new ImageLoader.Builder().url(imgUrl).imgView(mThumbnail).build());
        constructLabels(product.getExtendJson());
    }

    /**
     * 产品详情
     */
    void startProductDetail() {
        Intent intent = new Intent(getContext(), ActProductDetail.class);
        intent.putExtra("newProductInfo", currentProduct);
        intent.putExtra("data_from", DATATYPE_SEARCHED);
        intent.putExtra("company_follow_state", currentProduct.getFollowState());
        getContext().startActivity(intent);
    }

    public void setChecked(boolean checked) {
        mSelect.setOnCheckedChangeListener(null);
        mSelect.setChecked(checked);
    }

    /**
     * 返回产品主键
     *
     * @return
     */
    public int getProductId() {
        return currentProduct.getProductId();
    }


    public void constructLabels(List<ResponseProductTag.TagsBean> tagsBeens) {
        mLabelContainer.removeAllViews();
        if (tagsBeens == null || tagsBeens.size() <= 0) {
            return;
        }
        GradientDrawable myGrad;
        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
        lp.rightMargin = 15;
        lp.topMargin = 15;
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss", Locale.getDefault());
        try {
            ResponseProductTag.TagsBean tagsBean = null;
            for (int i = 0; i < tagsBeens.size(); i++) {
                tagsBean = tagsBeens.get(i);
                final String tagName = tagsBean.getTagname();
                final String startTime = tagsBean.getTagstarttime();
                final String endTime = tagsBean.getTagendtime();
                final String url = tagsBean.getTagurl();
                final String textColor = tagsBean.getForecolor();
                final String bgColor = tagsBean.getBackcolor();
                Date dStart = dateFormat.parse(startTime);
                Date dEnd = dateFormat.parse(endTime);
                Date dCurrent = DateUtils.getCurrentTimeDate();
                if (dCurrent.after(dStart) && dCurrent.before(dEnd)) {
                    TextView t = new TextView(getContext());
                    t.setText(tagName);
                    t.setTextSize(10);
                    t.setGravity(Gravity.CENTER);
//                    t.setTextColor(Color.parseColor("#ff858585"));
                    t.setTextColor(Color.parseColor(bgColor));
                    mLabelContainer.addView(t, lp);
                    t.setBackgroundResource(R.drawable.wiki_label_bg);
                    myGrad = (GradientDrawable) t.getBackground();
                    myGrad.setStroke(2, Color.parseColor(bgColor));
                    if (url != null && url.length() > 0) {
                        t.setOnClickListener(new OnClickListener() {
                            @Override
                            public void onClick(View arg0) {
                                Uri uri = Uri.parse(url);
                                Intent it = new Intent(Intent.ACTION_VIEW, uri);
                                getContext().startActivity(it);
                            }
                        });
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void drawLabels(List<ProductTag> tagsBeens) {
        mLabelContainer.removeAllViews();
        if (tagsBeens == null || tagsBeens.size() <= 0) {
            return;
        }
        try {
            GradientDrawable myGrad;
            LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
            lp.rightMargin = 15;
            lp.topMargin = 15;
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss", Locale.getDefault());
            ProductTag tagsBean = null;
            for (int i = 0; i < tagsBeens.size(); i++) {
                tagsBean = tagsBeens.get(i);
                final String tagName = tagsBean.getTagName();
                final String startTime = tagsBean.getTagStartTime();
                final String endTime = tagsBean.getTagEndTime();
                final String url = tagsBean.getTagUrl();
                final String textColor = tagsBean.getForeColor();
                final String bgColor = tagsBean.getBackColor();
                Date dStart = dateFormat.parse(startTime);
                Date dEnd = dateFormat.parse(endTime);
                Date dCurrent = DateUtils.getCurrentTimeDate();
                if (dCurrent.after(dStart) && dCurrent.before(dEnd)) {
                    TextView t = new TextView(getContext());
                    t.setText(tagName);
                    t.setTextSize(10);
                    t.setGravity(Gravity.CENTER);
//                    t.setTextColor(Color.parseColor("#ff858585"));
                    t.setTextColor(Color.parseColor(bgColor));
                    mLabelContainer.addView(t, lp);
                    t.setBackgroundResource(R.drawable.wiki_label_bg);
                    myGrad = (GradientDrawable) t.getBackground();
                    myGrad.setStroke(2, Color.parseColor(bgColor));
                    if (url != null && url.length() > 0) {
                        t.setOnClickListener(new OnClickListener() {
                            @Override
                            public void onClick(View arg0) {
                                Uri uri = Uri.parse(url);
                                Intent it = new Intent(Intent.ACTION_VIEW, uri);
                                getContext().startActivity(it);
                            }
                        });
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
